<template>
  <el-dialog :title="title" :visible.sync="visible" width="800px" :close-on-click-modal="false"	>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="18">
          <el-form-item label="店铺" prop="deptId">
            <el-cascader
              v-model="form.deptIds"
              :options="options.deptOptions"
              :show-all-levels="true"
              filter clearable
              placeholder="请选择店铺"
              @change="handleDeptChange"
              style="width: 100%"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="顺序" prop="orderNum">
            <el-input v-model="form.orderNum" type="number" placeholder="顺序" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="商品" prop="gNumber">
        <el-button type="primary" size="mini" @click="handleSelectGoods" >选择商品</el-button>
        <div class="card-list-container">
          <template v-for="(item, index) in shopGoods">
            <item-card :goods="item" :index="index" @delGoods="handleDelGoods" />
          </template>
        </div>
      </el-form-item>
      <el-form-item label="上架状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择上架状态" disabled>
          <el-option
            v-for="dict in dict.type.sys_goods_sj_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="delFlag">
        <el-radio-group v-model="form.delFlag">
          <el-radio
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.value"
          >{{dict.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <main-select ref="mainSelect" :dept-id="form.deptId" @success="handleSelectSuccess" />

  </el-dialog>

</template>

<script>
import { addShop, shopTreeSelect, findMaxOrderNum } from '@/api/goods/shop'

import ItemCard from '@/views/goods/list/itemCard.vue'

import MainSelect from '@/views/goods/main/select.vue'

export default {
  dicts: ['sys_normal_disable', 'sys_goods_sj_status'],
  components: { MainSelect, ItemCard },
  data() {
    return {
      visible: false,
      title: '添加商品',
      options: {
        deptOptions: []
      },
      // 表单参数
      form: {},
      shopGoods: [],
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "店铺不能为空", trigger: "blur" }
        ],
        'params.gNumbers': [
          { required: true, message: "商品编码不能为空", trigger: "change" }
        ],
        delFlag: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      }
    }
  },
  methods: {
    resetFrom() {
      this.shopGoods = [];
      this.form = {
        gshopId: undefined,
        deptId: undefined,
        deptIds: undefined,
        deptName: undefined,
        goodsName: undefined,
        orderNum: 1,
        delFlag: '0',
        status: '0',
        remark: undefined,
        params: {
          gNumbers: []
        }
      }
    },
    /** 查询部门下拉树结构 */
    shopTreeSelect() {
      shopTreeSelect().then(res => {
        this.options.deptOptions = res.data;
      });
    },
    show() {
      this.shopTreeSelect();
      this.resetFrom();
      this.visible = true
    },
    cancel() {
      this.resetFrom();
      this.visible = false;
    },
    submitForm() {
      if (this.form.params.gNumbers && this.form.params.gNumbers.length > 0) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (!this.form.gshopId) {
              addShop(this.form).then(response => {
                this.$modal.msgSuccess("添加成功");
                this.visible = false;
                this.$emit('success');
              });
            }
          }
        });
      } else {
        this.$modal.msgError('请先选择要添加的商品');
      }
    },
    handleSelectGoods() {
      if (this.form.deptId) {
        this.$refs.mainSelect.show();
      } else {
        this.$modal.msgError('请先选择店铺')
      }
    },
    handleSelectSuccess(val) {
      this.shopGoods = val;
      this.form.params.gNumbers = val.map(item => {return item.gNumber;})
    },
    handleDelGoods(index) {
      console.log('add handleDelGoods: ', index);
      if (this.shopGoods.length > index) {
        this.shopGoods.splice(index, 1);
        this.form.params.gNumbers.splice(index, 1);
      }
    },
    handleDeptChange() {
      this.form.deptId = this.getLastValueByArray(this.form.deptIds);
      this.shopGoods = [];
      this.form.params.gNumbers = [];
      if (this.form.deptId) {
        this.form.deptName = this.getDeptName(this.options.deptOptions, this.form.deptId);
        findMaxOrderNum(this.form.deptId).then((res) => {
          this.form.orderNum = res.data;
        })
      }
    },
    getDeptName(options, deptId) {
      let deptName = null;
      if (options && options.length > 0) {
        for (let i = 0, len = options.length; i < len; i++) {
          if (deptId === options[i].value) {
            deptName = options[i].object.deptName;
            i = len;
          } else if (options[i].children) {
            deptName = this.getDeptName(options[i].children, deptId);
            if (deptName) {
              i = len;
            }
          }
        }
      }
      return deptName;
    },
    /** 获取 cascader 值的末位 id */
    getLastValueByArray(arr) {
      if (arr && arr.length > 0) {
        return arr[arr.length -1];
      }
      return null;
    },
  }
}
</script>

<style scoped>

.card-list-container {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
}
</style>
